package map;

import java.util.*;

/**
 * @description: <a href="https://leetcode.cn/problems/group-anagrams/description/?envType=featured-list&envId=2cktkvj?envType=featured-list&envId=2cktkvj">49. 字母异位词分组</a>
 * @author: zhaoyinglin
 * @date: 2024/3/6
 */
public class GroupAnagrams {
    public static void main(String[] args) {
        // String[] strs = { "eat", "tea", "tan", "ate", "nat", "bat" };
        // Solution2 solution2 = new Solution2();
        // List<List<String>> lists = solution2.groupAnagrams(strs);
        //
        char[] chars = new char[] { 'a', 'b', 'c' };
        String str = new String(chars);

        System.out.println(str);

    }

    /**
     * 使用Map
     */
    class Solution1 {
        public List<List<String>> groupAnagrams(String[] strs) {

            Map<String, List<String>> map = new HashMap<>();

            for (String str : strs) {
                char[] chars = str.toCharArray();

                Arrays.sort(chars);

                String sortedStr = new String(chars);

                List<String> strings = map.getOrDefault(sortedStr, new ArrayList<>());

                strings.add(sortedStr);

                map.put(sortedStr, strings);
            }
            List<List<String>> result = new ArrayList<>();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                result.add(entry.getValue());
            }

            return result;
        }

    }

    /**
     * 计数统计
     */
    static class Solution2 {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for (String str : strs) {
                int[] counts = new int[26];
                int length = str.length();
                for (int i = 0; i < length; i++) {
                    counts[str.charAt(i) - 'a']++;
                }
                // 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串，作为哈希表的键
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < 26; i++) {
                    if (counts[i] != 0) {
                        sb.append((char) ('a' + i));
                        sb.append(counts[i]);
                    }
                }
                String key = sb.toString();
                System.out.println("key:" + key);
                List<String> list = map.getOrDefault(key, new ArrayList<String>());
                list.add(str);
                map.put(key, list);
            }
            return new ArrayList<List<String>>(map.values());
        }
    }
}


